# import datetime

from datetime import *
from LSTM.variableset import EMVar
import numpy as np
from dateutil.parser import parse
import pandas as pd

def get_offset_day(d, days=0, seconds=0, minutes=0, hours=0, weeks=0):
    return d + timedelta(days,seconds,minutes,hours,weeks)

def get_offset_day_str(d, days=0, seconds=0, minutes=0, hours=0, weeks=0, formater='%Y-%m-%d %HH:%MM'):
    date_time = get_offset_day(d, days, seconds, minutes, hours, weeks)
    return date_time.strftime(formater)




def get_next_offset_work_day(day=datetime.now(), offset=1):
    if isinstance(day, str):
        start = parse(day)
    else:
        start = parse(day.strftime(EMVar.FORMATE_YMD))
    if datetime.now().hour >=0 and datetime.now().hour <= 15:
        offset = offset-1
    if offset < 0:
        s1 = pd.bdate_range(end=start, periods=abs(offset)+1)
        return s1[0]
    else:
        s1 = pd.bdate_range(start=start, periods=abs(offset)+1)
        return s1[-1]

    # now = day
    # delta = offset
    # if now.isoweekday()==4:
    #     delta = 3+offset
    # if now.isoweekday()==5:
    #     delta = 2+offset
    # if now.isoweekday()==6:
    #     delta = 1+offset
    # else:
    #     delta = offset
    # next_offset_work_day = now + timedelta(days=delta)
    # return datetime.combine(next_offset_work_day, time())

"""
获取最近的工作日，如果是周六日返回周五，如果是周一到周五直接返回当天
"""
def get_last_work_day(day=date.today(), formatter=None):
    now=day
    if now.isoweekday()==6:
      dayStep=1
    elif now.isoweekday()==7:
      dayStep=2
    else:
      dayStep=0
    lastWorkDay = now - timedelta(days=dayStep)
    if formatter:
        return lastWorkDay.strftime(formatter)
    return lastWorkDay

def delta_date(t1, t2):
    if isinstance(t1, datetime) and isinstance(t2, datetime):
        return {EMVar.DAY:(t1-t2).days,
                EMVar.HOUR:int((t1-t2).total_seconds()/3600),
                EMVar.MIN:int((t1-t2).total_seconds())/60,
                EMVar.SEC: int((t1 - t2).total_seconds())}


def delta_date_str(t1, t2, formatter=EMVar.FORMATE_YMD):
    if isinstance(t1, str) and isinstance(t2, str):
        t1_ = datetime.strptime(t1, formatter)
        t2_ = datetime.strptime(t2, formatter)
        return delta_date(t1_, t2_)


def delta_work_days_str(begin, end):
    days = np.busday_count(begin, end)
    return days




def reformater(str_t, formatter=EMVar.FORMATE_YMD):
    return parse(str_t).strftime(formatter)

# str = get_offset_day_str(datetime.now(), days=1)
# last_work_day = get_last_work_day(formatter=EMVar.FORMATE_YMD)
# delta_days = delta_work_days_str('2017-10-02','2017-10-02')
# get_next_offset_work_day(offset=-1)
pass




